import time
import base64
from django.shortcuts import render
import json

from redis import Redis
# Create your views here.
from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from django.conf import settings
from .models import UserModel, UserRole, Role, RoleResource, Resource, personRole, deposit, privacy, ServiceOrder, \
    WithModel, Service, Workflow, WorkflowPermission
from .serializer import UserSerializer, ResourceSerializer, UserRoleSerializer, Peoplerole, DepositSerializer, \
    PrivacySerializer, OrderSerializer, WithSer, ServiceSer, RoleSerializer, UserResourceSerializer, WorkflowSerializer, \
    WorkflowPermissionSerializer

from .serializer import UserSerializer,ResourceSerializer,UserRoleSerializer,Peoplerole,DepositSerializer,PrivacySerializer,OrderSerializer,WithSer,ServiceSer,RoleSerializer,RoleResourceSerializer

from .models import UserModel,UserRole,Role,RoleResource,Resource,ResourceInterface

from django.contrib.auth.hashers import make_password,check_password
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from .myjwt import myjwt
from django_redis import get_redis_connection

redis = get_redis_connection("url")




#自定义token载荷的内容
# class CoustomTokenObtainPairSerializer(TokenObtainPairSerializer):
#     @classmethod
#     def get_token(cls, user):
#         token = super().get_token(user)
#         token["id"] = str(user.id)
#         token['username'] = str(user.username)
#         token['mobile'] = str(user.mobile)
#         token['avatar'] = str(user.avatar)
#         token['email'] = str(user.email)
#         return token
#注册功能
class RegisterAPIView(APIView):
    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)





from django.contrib.auth import authenticate

class LoginAPIView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        # 查找用户
        user = UserModel.objects.filter(username=username).first()
        print(user)
        # 检查用户是否存在
        if user is not None:
            # 验证密码
            if check_password(password, user.password):
                if user.is_active:
                    # 可以在这里添加token生成逻辑
                    useradmin = UserRole.objects.filter(userid=user).first()
                    print(useradmin)
                    list = useradmin.roleid.roles.all()
                    # print(list,"+++++++========")

                    if useradmin:
                        role = useradmin.roleid
                        # 获取角色对应的所有资源ID
                        resource_ids = role.roles.values_list('resourceid', flat=True)
                        workflow_ids = role.role_workflow.values_list('workflowid',flat=True)

                        # 使用资源ID来获取对应的资源权限表
                        print(resource_ids,"++++++++++++++++++++++---------------")
                        print(workflow_ids,"---------------++++++++++++++++++++++")
                        interfaces = ResourceInterface.objects.filter(resid__in=resource_ids)
                        print(interfaces, "路径资源1245454")
                        workflows = WorkflowPermission.objects.filter(workflowid__in=workflow_ids)
                        print(workflows, "路径资源777777")
                        # 接口权限
                        interface = []
                        for res in interfaces:
                            interface.append(res.url)
                        print(interface)
                        # 工作流权限
                        workflow = []
                        for res in workflows:
                            workflow.append(res.roleid_id)
                        print(workflow)
                        permissions = {
                            'interface': interface,
                            'workflow': workflow
                        }

                        # 将字典序列化为 JSON 字符串
                        # permissions_json = json.dumps(permissions)
                        # 将 JSON 字符串存储到 Redis
                        # redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
                        # redis_client = Redis(host='localhost', port=6379, db=0)
                        # redis_client.set(f'user{user.id}permissions', permissions_json)
                        redis.set(f'user{user.id}promition',json.dumps(interface))
                        # redis.set(f'user{user.id}workflow',json.dumps(workflow))

                    # for i in list:
                    #     # print("角色",i.roleid.name)
                    #     print("标题id",i.resourceid.id)
                    #     print("标题",i.resourceid.name)
                    #     print("路由",i.resourceid.url)
                    #     print("是否是二级标题",i.resourceid.pname)
                    #     print("是否是二级标题",i.resourceid.pname_id)
                    #     print("是否是三级标题",i.resourceid.sname)
                    #     print("是否是三级标题",i.resourceid.sname_id)
                    #
                    #     print("________________________________________________")
                    list = xtree(list)
                    # 返回响应
                    token = myjwt.jwt_encode({"userid":user.id,"username":str(user.username),"mobile":user.mobile,"email":user.email,"exp":int(time.time())+60*60*20})
                    # print(token)
                    # print(myjwt.jwt_decode(token))
                    return Response({"message": "登录成功111","data":list,"avatar":user.avatar.url,"token": token }, status=status.HTTP_200_OK)
                else:
                    return Response({"message": "账户未激活"}, status=status.HTTP_401_UNAUTHORIZED)
            else:
                return Response({"message": "密码错误"}, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response({"message": "用户名不存在"}, status=status.HTTP_401_UNAUTHORIZED)

# [{"id":1,"name":"权限管理","son":[{"id":2,"name":"资源管理","son1":[{"id":2,"name":"资源管理"}},{"id":2,"name":"角色管理"}]}]
def xtree(data):
    if len(data) <= 0:
        return data
    plist1 = []
    ids1 = []

    for i in data:
        # print("角色",i.roleid.name)
        # print("标题id", i.resourceid.id)
        # print("标题", i.resourceid.name)
        # print("路由", i.resourceid.url)
        # print("是否是二级标题", i.resourceid.pname)
        # print("是否是二级标题", i.resourceid.pname_id)
        # print("是否是三级标题", i.resourceid.sname)
        # print("是否是三级标题", i.resourceid.sname_id)
        if i.resourceid.pname is None and i.resourceid.sname is None:
            if i.resourceid.id not in ids1:
                plist1.append({"id": i.resourceid.id, "name": i.resourceid.name, "url": i.resourceid.url,"son": []})
                ids1.append(i.resourceid.id)
    print(plist1,"-------------------------------")
    for i in data:
        for j in plist1:  # 直接遍历 plist1，不需要使用 enumerate
            print("++++++++++++++")
            print(j.get("id"))  # 使用 get 方法访问字典键
            print(i.resourceid.pname_id)
            if j["id"] == i.resourceid.pname_id and i.resourceid.sname_id is None:  # 比较 id 值
                j['son'].append({"id": i.resourceid.id, "name": i.resourceid.name, "url": i.resourceid.url, "son1": []})

    for i in data:
        for x in plist1:
            # print(x,"111111111")
            for j in x["son"]:
                if j["id"] == i.resourceid.sname_id:
                #添加进son1中
                    j['son1'].append({"id": i.resourceid.id, "name": i.resourceid.name, "url": i.resourceid.url})


    return plist1



    # plist = []
    # ids = []
    # for i in data:
    #     if i['pid'] not in ids:
    # dict = {"id": i['pid'], "name": i['pname'], "son": []}
    # plist.append(dict)
    # ids.append(i['pid'])
    #
    #
    # for j in data:
    #     for (i, index) in enumrate(plist):
    #         if j['pid'] = i['id']:
    #             plist[index]['son'].append({"id": j['id'], "name": j["name"], "url": j["url"]})









#资源表
class ResourceAPIView(APIView):
    def get(self, request):
        resource = Resource.objects.all()
        resoure_ser = ResourceSerializer(instance=resource, many=True)
        return Response(resoure_ser.data)




#刷新token_api
class RefreshTokenAPIView(APIView):
    def post(self, request):
        data = myjwt.jwt_decode("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjIsInVzZXJuYW1lIjoiYWRtaW4iLCJtb2JpbGUiOiIxNTIzNzc3OTI0MCIsImVtYWlsIjoiYWRtaW4xMjNAcXEuY29tIiwiZXhwIjoxNzMyMzA5ODU1LCJyZWZyZXNoIjoxNzMyMzEzNDU1fQ.Upb561CTAe77mQbaArgvFPTRkmc1HuWjslO-QB6X1hQ")
        data['exp'] = int(time.time()) + 60 * 60 * 20
        token = myjwt.jwt_encode(data)
        return Response({'message': '刷新成功', 'token': token}, status=status.HTTP_200_OK)
        #获取请求头中的token
        # token = request.headers.get('Authorization')
        # if token:
        #     try:
        #         data = myjwt.jwt_decode(token)
        #         #判断refresh_token是否过期
        #         if data['exp']+60*60*1 < int(time.time()):
        #             return Response({'message': '请先重新登录'}, status=status.HTTP_403_FORBIDDEN)
        #         data['exp'] = int(time.time()) + 60 * 60 * 20
        #         token = myjwt.jwt_encode(data)
        #         return Response({'message': '刷新成功', 'token': token}, status=status.HTTP_200_OK)
        #     except Exception as e:
        #         return Response({'message': '刷新失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     return Response({'message': '请先登录'}, status=status.HTTP_403_FORBIDDEN)

#新增退出逻辑
class QuitViewApi(APIView):
    def get(self, request):
        #获取请求头中的token

        token = request.headers.get('Authorization')
        print(token,'==0顶321312313')
        #以token为key,设置过期时间,查看过期时间
        # token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjIsInVzZXJuYW1lIjoiYWRtaW4iLCJtb2JpbGUiOiIxNTIzNzc3OTI0MCIsImVtYWlsIjoiYWRtaW4xMjNAcXEuY29tIiwiZXhwIjoxNzMyMzI0NTAyfQ.CAR4njnhl4H29NM5TxQHytP91IZE4YCQjJyEta44dq8"
        # data = myjwt.jwt_decode(token)
        # print(data["exp"])
        #存入redis,设置过期时间
        redis.setex(token, 60*60*20,1245)
        #查询token
        # print(redis.get(token))
        return Response({'message': '退出成功'}, status=status.HTTP_200_OK)



# 用户角色表
class UserRoleView(APIView):
    def get(self, request):
        userrole = personRole.objects.all()
        userrole_ser = UserRoleSerializer(instance=userrole, many=True)
        return Response(userrole_ser.data)



class Page(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'size'
    page_query_param = 'page'
# 人员管理
class PersonView(ModelViewSet):
    queryset = personRole.objects.all()
    serializer_class = Peoplerole
    pagination_class = Page


# 保证金管理
class DepositView(ModelViewSet):
    queryset = deposit.objects.all()
    serializer_class = DepositSerializer
    pagination_class = Page


# 隐私协议
class PrivacyView(ModelViewSet):
    queryset = privacy.objects.all()
    serializer_class = PrivacySerializer


# 订单表
class OrderView(ModelViewSet):
    queryset = ServiceOrder.objects.all()
    serializer_class = OrderSerializer
    pagination_class = Page




# 提现
class WithView(ModelViewSet):
    queryset = WithModel.objects.all()
    serializer_class = WithSer
    pagination_class = Page
# 服务表
class ServiceView(ModelViewSet):
    queryset = Service.objects.all()
    serializer_class = ServiceSer
    pagination_class = Page






# 角色筛选功能实现添加角色继承
from rest_framework.generics import ListAPIView, CreateAPIView
from django_filters.rest_framework import FilterSet
import django_filters

class PageRole(FilterSet):
    sisbase = django_filters.NumberFilter(field_name='isbase')
    class Meta:
        model = Role
        fields = ['sisbase']

# 角色表
class RoleView(ListAPIView):
    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    filterset_class = PageRole
# class RolesView(ModelViewSet):
#     queryset = Role.objects.all()
#     serializer_class = RoleSerializer

    # def perform_create(self, serializer):
    #     # 创建角色
    #     role = serializer.save()
    #     # 获取资源数据
    #     resources_data = serializer.initial_data.get('resources', [])
    #     # 为每个资源创建 RoleResource 记录
    #     for resource_data in resources_data:
    #         resource_id = resource_data.get('resourceid_id')
    #         if resource_id:  # 确保 resource_id 不是 None 或空字符串
    #             try:
    #                 resource = Resource.objects.get(id=resource_id)
    #                 RoleResource.objects.create(roleid=role, resourceid=resource)
    #             except Resource.DoesNotExist:
    #                 # 如果资源ID不存在，则记录错误或跳过
    #                 print(f"Resource with id {resource_id} does not exist.")
    #                 continue


    # def create(self, request, *args, **kwargs):
    #     serializer = self.get_serializer(data=request.data)
    #     if serializer.is_valid():
    #         self.perform_create(serializer)
    #         return Response(serializer.data, status=status.HTTP_201_CREATED)
    #     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# class RoleResourceAPIView(APIView):
#     def get(self, request, role_id):
#         role_resources = RoleResource.objects.filter(roleid_id=role_id)
#         serializer = RoleResourceSerializer(role_resources, many=True)
#         return Response(serializer.data)


# 角色资源表
class UserResourceView(ModelViewSet):
    queryset = RoleResource.objects.all()
    serializer_class = UserResourceSerializer



class RoleResourceFilter(FilterSet):
    sroleid = django_filters.NumberFilter(field_name='roleid')
    class Meta:
        model = RoleResource
        fields = ['sroleid']


# 角色资源实现下拉选框选中继承角色时,自动选中对应的资源
class RoleResourceView(ListAPIView):
    queryset = RoleResource.objects.all()
    serializer_class = RoleResourceSerializer
    filterset_class = RoleResourceFilter


#角色继承后入库post逻辑
class AddARole(CreateAPIView):
    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    #重写post方法, 实现角色继承,
    def post(self, request, *args, **kwargs):
        data = request.data
        print(data)
        #首先先判断是否有region,基础角色id有的话证明选择了继承角色,无则没有继承角色
        # if not data.get("region"):
        #     #角色表新增名称,角色资源表新增角色id,对应的资源id
        #     role = Role.objects.create(name=data.get("name"), pid="",isbase=0)
        #     for i in data.get("type"):
        #         RoleResource.objects.create(roleid=role, resourceid=i)
        # else:
        if data.get("region"):
            #有region,角色继承了基础角色,需要特殊处理,新增角色,新增角色资源(post过来的资源id,获取到继承角色的资源id,取
            region = Role.objects.get(id=data.get("region")).roles.all()
            #基础角色的资源id
            reglist = []
            for i in region:
                reglist.append(i.id)
            print(reglist)
            #利用集合求差集
            difference = list(set(data.get("type")) - set(reglist))
            print(difference)


            # role = Role.objects.create(name=data.get("name"), pid=data.get("region"), isbase=0)
            # for i in data.get("type"):
            #     RoleResource.objects.create(roleid=role, resourceid=i)

        return Response({"msg": "ok"}, status=status.HTTP_201_CREATED)


class WorkflowView(ModelViewSet):
    queryset = Workflow.objects.all()
    serializer_class = WorkflowSerializer

class WorkflowPermissionView(ModelViewSet):
    queryset = WorkflowPermission.objects.filter()
    serializer_class = WorkflowPermissionSerializer








